package fr.umlv.ig.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import fr.umlv.ig.event.StationEvent;

public class MetroModelImpl extends AbstractMetroModel {

	private final Map<String,Line> lines;
	
	private final List<Line> lineList;
	
	
	public MetroModelImpl() {
		lines = new HashMap<String, Line>();
		lineList = new ArrayList<Line>();
	}
	
	@Override
	public int getLineCount() {
		return lines.size();
	}
	
	@Override
	public Line getLine(String lineNumber) {
		return lines.get(lineNumber);
	}
	
	public Line getLine(int index) {
		return lineList.get(index);
	}
	
	@Override
	public Station getStation(Line line, int index) {
		return line.getStation(index);
	}
	
	public void openStation(Station station ) {
		if(station == null || station.isOpened()) {
			return;
		}
		station.setOpened(true);
		fireStationChanged(new StationEvent(station, StationEvent.STATION_OPENED));
	}

	public void closeStation(Station station ) {
		if(station == null || !station.isOpened()) {
			return;
		}
		station.setOpened(false);
		
		//ajouter fire
	}
		
	public void addTrain(Train train) {
		
	}

	public void removeTrain(Train train) {
		//ajouter fire
	}

	


//Next methods ares used just for the initialization of the Model
	
	public void addStation(Line line, Station station) {
		if(line == null) {
			throw new NullPointerException("the line is null");
		}
		line.addStation(station);
		fireIntervalStationAdded(line, line.indexOf(station),line.indexOf(station));
	}
	
	public void addNextStation(Line line, Station direction, Station station, Station nextStation) {
		if(line == null) {
			throw new NullPointerException("the Line is null");
		}
		if(!line.contains(direction) || !line.contains(station) || !line.contains(nextStation)) {
			throw new IllegalArgumentException("stations are not in the Line");
		}
		station.addNextStation(direction, nextStation);
		int index0 = line.indexOf(station);
		int index1 = line.indexOf(nextStation);
		if(index0 < index1) {
			fireIntervalStationAdded(line, index0,index1);
		}
		else {
			fireIntervalStationAdded(line, index1,index0);
		}
	}
	
	public void addLine(Line line) {
		if(line==null) {
			throw new IllegalArgumentException("The line is null");
		}
		if(lines.containsKey(line.getNumber())) {
			throw new IllegalArgumentException("The Line is already in the model.");
		}
		lineList.add(line);
		lines.put(line.getNumber(), line);
		//Ajouter Listener
	}
	
	public void addItinerary(Line line, Itinerary itinerary) {
		if(line == null) {
			throw new NullPointerException("the line is null");
		}
		if(!lines.containsKey(line.getNumber())) {
			throw new IllegalArgumentException("The line is not in the Model");
		}
		line.addItinaries(itinerary);
		//ajouter listener
	}
	


}
